/*----------------------------- 后台保存的状态数据 -----------------------------*/
var STATUS = {
    communication: {
        port: null
    },
    category: [],
    domain: 'http://localhost',    // 域名
    api: 'http://127.0.0.1:8085',  // 后端接口
    home: 'http://localhost:8080', // 网站主页
    username: '',
    token: '',
    isLogin: false
}

// 右键菜单设置
chrome.contextMenus.create({
    id: 'sharelinks-parent0',
    title: "收藏当前网址到"
});


/*----------------------------- 事件监听 -----------------------------*/
chrome.runtime.onInstalled.addListener(function () {
    getCategory();
    checkLogin();
});

// 页面刷新事件监听(新建标签页)
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (changeInfo.url === undefined && changeInfo.status == 'complete') {
        console.log('refresh...');

        if (STATUS.category.length < 1) {
            getCategory();
        }

        // 每次页面刷新时，都会检测登陆信息是否正确
        checkLogin();
    }
});

chrome.tabs.onCreated.addListener(function (tab) {

    //chrome.tabs.executeScript(tab.id, {file: '../js/content.js'});
});

// 工具栏按钮点击事件监听
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({url: STATUS.home});
});


/*----------------------------- 和其他组件进行通信 -----------------------------*/

// 和browser_action进行通信
chrome.extension.onConnect.addListener(function (port) {
    STATUS.communication.port = port;

    port.onMessage.addListener(function (msg) {
        if (msg == 'isLogin') port.postMessage({loginStatus: STATUS.isLogin});
    });
});

// 向content_script发送消息
function sendToContentScript(action, msg) {
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            action: action,
            msg: msg
        });
    });
}

/*----------------------------- 工具方法 -----------------------------*/

// 添加到收藏
function add2collection(url, title, category) {
    console.log('add2collection...');
    if (STATUS.username == '' || STATUS.token == '') {
        // 收藏失败，尚未登陆
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {action: "add_to_collection_error", msg: "尚未登陆"});
        });
    } else {
        fetch(STATUS.api + '/posts/add', {
            method: "POST",
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify({
                url: url,
                title: title,
                category: category,
                username: STATUS.username,
                token: STATUS.token
            }),
        }).then(
            response => {
                response.json().then(value => {
                    if (value.code > 0) {
                        sendToContentScript("add_to_collection_success", "收藏成功");
                    } else {
                        if (value.msg=='repetitive') {
                            sendToContentScript("warning", "链接已收藏");
                        } else {
                            sendToContentScript("add_to_collection_error", "收藏错误");
                        }

                    }
                });
            },error => {
                sendToContentScript("add_to_collection_error", "收藏错误");
            }
        );
    }
}

// 检测用户是否登陆
function checkLogin() {
    chrome.cookies.getAll({url: STATUS.domain}, function (cookies) {
        if (cookies != undefined && cookies != null) {
            cookies.forEach(function (element) {
                if (element.name == 'username') {
                    STATUS.username = element.value;
                }

                if (element.name == 'token') {
                    STATUS.token = element.value;
                }
            });

            // 检测用户登陆信息是否有效
            fetch(STATUS.api + '/user/detect', {
                method: "POST",
                headers: {
                    'content-type': 'application/json'
                },
                body: JSON.stringify({
                    username: STATUS.username,
                    token: STATUS.token
                }),
            }).then(
                response => {
                    var jsonObj = response.json();
                    jsonObj.then(value => {
                        if (value.code > 0) {
                            STATUS.isLogin = true;
                        } else {
                            STATUS.username = '';
                            STATUS.token = '';
                        }
                    });
                }
            );
        }
    });
}

// 获取分类
function getCategory() {
    fetch(STATUS.api + '/category/all', {
        method: "GET",
        body: null,
    }).then(
        response => {
            var jsonObj = response.json();
            jsonObj.then(value => {
                value.forEach(function (item) {
                    STATUS.category.push(item.fname);
                    chrome.contextMenus.create(
                        {
                            parentId: 'sharelinks-parent0',
                            title: item.fname,
                            onclick: function (info, tab) {
                                if (tab == undefined || tab == null) tab = {title: 'tab is null'};
                                add2collection(info.pageUrl, tab.title, item.fname);
                            }
                        });
                });
            });
        }
    ), error => {
        sendToContentScript("error", "网络连接失败");
    };
}